<template>
    <div class="container">
        <!-- 左侧导航栏 -->
        <aside :style="{ color: theme === 'light' ? '#000' : '#fff' }" class="sidebar">
            <!-- 背景图片区域 -->
            <div class="background" :style="{
                backgroundImage: backgroundUrl ? `url(${backgroundUrl})` : 'none',
                backgroundColor: !backgroundUrl ? (theme === 'light' ? '#ffffff' : '#333333') : 'transparent',
            }"></div>

            <!-- 上传背景图片按钮 -->
            <div class="upload-container">
                <label for="upload-background" class="upload-label">更换背景图片</label>
                <input id="upload-background" type="file" accept="image/*" @change="uploadBackground"
                    class="upload-input" />
                <label style="margin-left: 10px;" for="upload-quit" class="upload-label">退出</label>
                <button @click="quitApp()" id="upload-quit"></button>
            </div>
            <div class="userinfo">
                <img :src="`${config.downloadUrl}?name=${imgUrl}`" />
                <span style="margin-top: 20px; font-size: 25px; font-weight: 600;">{{ username }}</span>
            </div>
            <!-- 导航区域 -->
            <nav class="nav">
                <router-link v-for="(link, index) in navLinks" :key="index" :to="link.to"
                    :style="{ color: theme === 'light' ? '#000' : '#fff' }">
                    {{ link.text }}
                </router-link>
            </nav>
            <!-- 存在问题暂时禁用 -->
            <!-- <div :style="{ color: theme === 'light' ? '#000' : '#fff' }" class="proverb-container" :class="{ 'proverb-light': theme === 'light', 'proverb-dark': theme === 'dark' }">
                <span class="proverb-text">{{ displayProverb }}</span>
            </div> -->
        </aside>
        <!-- 添加顶部栏 -->
        <div class="top-bar" @mousedown="startDrag">
            <div class="window-controls">
                <button style="display: flex; align-items: center;" @click="minimize">
                    <el-icon>
                        <Minus />
                    </el-icon>
                </button>
                <button style="display: flex; align-items: center;" @click="maximize">
                    <el-icon>
                        <FullScreen />
                    </el-icon>
                </button>
                <button style="display: flex; align-items: center;" @click="handleClose()">
                    <el-icon>
                        <Close />
                    </el-icon>
                </button>
            </div>
            <!-- 存在问题暂时禁用 -->
            <!-- <button class="theme-toggle" @click="toggleTheme">切换主题</button> -->
        </div>
        <!-- 右侧内容区域 -->
        <main class="content">
            <router-view style="border-radius: 10px;margin-top: 35px;background-color: white;"></router-view>
        </main>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import config from '../../../public/config';
import { ElMessageBox, ElNotification } from 'element-plus';
import router from '../../router';
import { getByUserName } from '../../api/login';


const stompClient = ref()
const displayProverb = ref('');


// 当前主题
const theme = ref('light');

// 背景图片 URL（默认为空）
const backgroundUrl = ref('');
const imgUrl = ref('')
// 用户名
const username = localStorage.getItem('username');

// 导航链接数据
const navLinks = [
    { text: '社区', to: '/ForYou' },
    { text: '我的', to: '/userhome' },
    { text: 'DeepSeek', to: '/deepseek' },
    { text: '邀请', to: '/Come' }
    // {text: '关于', to: '/About'}
];

// 上传背景图片
const uploadBackground = (e) => {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = () => {
            backgroundUrl.value = reader.result; // 设置背景图片 URL
            localStorage.setItem('backgroundUrl', reader.result); // 保存到 localStorage
        };
        reader.readAsDataURL(file);
    }
};

// 切换主题
const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light';
    localStorage.setItem('theme', theme.value);
};

// 挂载时从 localStorage 恢复用户设置
onMounted(() => {
    const savedTheme = localStorage.getItem('theme');
    const savedBackground = localStorage.getItem('backgroundUrl');

    if (savedTheme) theme.value = savedTheme;
    if (savedBackground) backgroundUrl.value = savedBackground;
    connect()
    getUserMessage()
    getNotifition()
});

// 窗口操作
const minimize = () => {
    window.myApi.miniWindows();
};

const maximize = () => {
    window.myApi.maximizeWindow();
};

const handleClose = () => {
    ElMessageBox.confirm('您想最小化到托盘还是直接退出', '退出', {
        confirmButtonText: '直接退出',
        cancelButtonText: '最小化到托盘',
        distinguishCancelAndClose: true,
        type: 'warning',
    })
        .then(() => {
            // 直接退出
            window.myApi.quitApp();
        })
        .catch((action) => {
            if (action === 'cancel') {
                // 最小化到托盘
                window.myApi.closeWindows();
            }
        });
};

const quitApp = () => {
    ElMessageBox.confirm('确定要退出当前账号吗', '退出', {
        confirmButtonText: '退出',
        cancelButtonText: '点错了',
        distinguishCancelAndClose: true,
        type: 'warning',
    })
        .then(() => {
            localStorage.removeItem("username")
            localStorage.removeItem("token")
            localStorage.removeItem("tokenExpiry")
            router.push('/')
            ElNotification({
                title: '退出',
                message: '退出成功',
                type: 'success',
                showClose: false,
            })
        })
        .catch((action) => {
            ElNotification({
                title: '退出',
                message: '取消退出',
                type: 'warning',
                showClose: false,
            })
        });
}

// 打字机效果函数
const typeWriter = (text) => {
    displayProverb.value = ''; // 清空当前显示的文本
    let index = 0;

    const interval = setInterval(() => {
        if (index < text.length) {
            displayProverb.value += text.charAt(index); // 添加一个字符
            index++;
        } else {
            clearInterval(interval); // 完成后清除定时器
        }
    }, 100); // 每100毫秒添加一个字符
};

function connect() {

}

// 在组件卸载时断开连接
onBeforeUnmount(() => {
    if (stompClient.value) {
        stompClient.value.disconnect();
    }
});

const isDragging = ref(false);
const startX = ref(0);
const startY = ref(0);
const initialX = ref(0);
const initialY = ref(0);
const NotificationUrl='../../../public/logo_quxie.ico'
const threshold = 10; // 增加阈值，避免拖动过小的位移

// 使用 requestAnimationFrame 实现平滑拖动
let animationFrameId = null;

// 开始拖动
const startDrag = (event) => {
    isDragging.value = true;
    startX.value = event.clientX;
    startY.value = event.clientY;
    initialX.value = window.screenX;
    initialY.value = window.screenY;

    window.addEventListener('mousemove', dragWindow); // 使用原生的mousemove监听
    window.addEventListener('mouseup', stopDrag);
};

// 拖动窗口
const dragWindow = (event) => {
    if (!isDragging.value) return;

    const moveX = event.clientX - startX.value;
    const moveY = event.clientY - startY.value;

    // 仅当移动超过阈值时才更新窗口位置
    if (Math.abs(moveX) > threshold || Math.abs(moveY) > threshold) {
        cancelAnimationFrame(animationFrameId); // 清除上一个帧
        animationFrameId = requestAnimationFrame(() => {
            window.moveTo(initialX.value + moveX, initialY.value + moveY);
        });
    }
};

// 停止拖动
const stopDrag = () => {
    isDragging.value = false;
    window.removeEventListener('mousemove', dragWindow);
    window.removeEventListener('mouseup', stopDrag);
};
async function getUserMessage() {
    let params = new URLSearchParams();
    params.append("username", localStorage.getItem("username"))
    await getByUserName(params)
        .then(res => {
            if (res.code == 200) {
                imgUrl.value = res.data.avatar
            } else if (res.code == 400) {
                ElNotification({
                    title: '头像获取失败',
                    message: res.message,
                    type: 'error',
                    showClose: false,
                });
            }
        })
}



// 获取通知
function getNotifition() {
    const userId = localStorage.getItem("userId");

    if (!userId) {
        setTimeout(getNotifition, 1000); // 1秒后再尝试初始化
        return;
    }
    const socket = new WebSocket(`${config.WS_URL}?userId=${userId}`);

    socket.onmessage = function (event) {
        ElNotification({
            title: '通知',
            type: 'info',
            message: event.data,
            position: 'bottom-right'
        })
            // 使用 Electron 的 Notification API 显示系统通知
        if (window.Notification && Notification.permission === 'granted') {
            new Notification('通知', {
            body: event.data + '请前往app查看'
            });
        } else {
            // 如果没有通知权限，可以请求用户授权
            Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
                new Notification('通知', {
                body: event.data + '请前往app查看'
                });
            }
            });
        }
    };

    socket.onerror = function (error) {
        console.error("WebSocket 错误:", error);
    };
}
</script>

<style scoped>
.container {
    display: flex;
    width: 100%;
    height: 100vh;
}

::-webkit-scrollbar {
    width: 10px;
}

::-webkit-scrollbar-track {
    background: #dfe4ed;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #4b79a1, #283e51);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #3b607e, #1b2e38);
}

.sidebar {
    width: 300px;
    position: relative;
    color: white;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transition: color 0.3s ease;
    border-radius: 10px 0px 0px 10px;
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 110%;
    height: 110%;
    background-size: cover;
    background-position: center;
    z-index: -1;
    filter: blur(10px);
    transition: background-color 0.3s ease;
}

.upload-container {
    position: absolute;
    bottom: 20px;
    left: 20px;
}

.upload-label {
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
}

.upload-input {
    display: none;
}

.nav {
    margin-top: 70px;
    display: flex;
    flex-direction: column;
    padding: 20px;
    align-items: center;
}

.nav a {
    text-decoration: none;
    margin: 10px 0;
    font-size: 20px;
    transition: color 0.3s ease;
}

.content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    transition: color 0.3s ease, filter 0.3s ease;
    filter: brightness(1);
    border-radius: 0px 10px 10px 0px;
    background-color: white;
}

.content.light {
    background-color: #ebebeb;
    color: #e3e3e3;
    filter: brightness(1);
}

.content.dark {
    background-color: #404040;
    color: #ffffff;
    filter: brightness(0.8);
}

.theme-toggle {
    position: fixed;
    top: 10px;
    right: 180px;
    padding: 10px 20px;
    background-color: #555;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.userinfo {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 50px;
}

.userinfo img {
    width: 120px;
    height: 120px;
    border-radius: 50%;
}

.window-controls {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    gap: 10px;
    z-index: 2;
}

.window-controls button {
    background: linear-gradient(135deg, #493186, #493186);
    border: none;
    color: white;
    font-size: 1.2rem;
    cursor: pointer;
    border-radius: 5px;
    padding: 8px 12px;
    transition: background-color 0.3s, transform 0.2s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.window-controls button:hover {
    background: linear-gradient(135deg, #493186, #493186);
    transform: scale(1.05);
}

.proverb-container {
    font-size: 17px;
    font-weight: 700;
    margin-top: 120px;
    white-space: normal;
    /* 允许换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    border-right: 2px solid #333;
    /* 打字机光标效果 */
    animation: blink 1s step-end infinite;
    /* 光标闪烁效果 */
    word-wrap: break-word;
    /* 超出宽度时换行 */
}

@keyframes blink {
    50% {
        border-color: transparent;
        /* 光标闪烁 */
    }
}

.proverb-light {
    background-color: rgba(255, 255, 255, 0.24);
    /* 浅色主题背景 */
    border-radius: 5px;
    /* 圆角 */
    padding: 10px;
    /* 内边距 */
}

.proverb-dark {
    background-color: rgba(0, 0, 0, 0.265);
    /* 深色主题背景 */
    border-radius: 5px;
    /* 圆角 */
    padding: 10px;
    /* 内边距 */
}

.top-bar {
    position: fixed;
    height: 30px;
    top: 0;
    left: 0;
    right: 0;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 10;
}
</style>
